package cn.fenghua.demoproject2.controller;

import cn.fenghua.demoproject2.dao.User;
import cn.fenghua.demoproject2.service.UserService;
import cn.fenghua.demoproject2.utils.JsonData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/pub/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public JsonData login(@RequestBody User user) {
        System.out.println(user.toString());

        String token = userService.login(user.getUsername(), user.getPwd());

        return token != null ? JsonData.buildSuccess(token) : JsonData.buildError("账号密码错误");
    }

    @RequestMapping("/list")
    public JsonData list() throws JsonProcessingException {
        List<User> list = userService.list();

        // 序列化
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(list);
        System.out.println(jsonStr);

        // 反序列化
        List<User> list1 = objectMapper.readValue(jsonStr, List.class);
        System.out.println(list1);
        return JsonData.buildSuccess(list1);
    }
}
